package com.microweb.toastmaster.webapp.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.microweb.toastmaster.Constants;
import com.microweb.toastmaster.model.Agenda;
import com.microweb.toastmaster.model.viewwrapper.AgendaWrapper;
import com.microweb.toastmaster.service.AgendaManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ShowAgendasController implements Controller {
    private final Log log = LogFactory.getLog(ShowAgendasController.class);
    private AgendaManager agendaManager = null;
    private int num_of_display = 5;
    
    public void setAgendaManager(AgendaManager agendaManager) {
        this.agendaManager = agendaManager;
    }

    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
        List<?> agendas = agendaManager.getAgendas(null);
        
        List<AgendaWrapper> agendaList = new ArrayList<AgendaWrapper>();
        if(request.getParameter("latest") != null) {
            for(int i=0; i<num_of_display && i<agendas.size(); i++) {
                agendaList.add(new AgendaWrapper((Agenda)agendas.get(i)));
            }
        }
        
        if(request.getParameter("month") != null) {
            Locale locale = Locale.US;
            SimpleDateFormat formatter
		= new SimpleDateFormat ("MM/yyyy", locale);
            Date inputDate = null;
            try {
                inputDate = formatter.parse(request.getParameter("month"));
            } catch(ParseException pex) {
                log.debug("input date format error!");
            }
            
            if(inputDate != null) {
                for(int i=0; i<agendas.size(); i++) {
                    Date agendaDate = ((Agenda)agendas.get(i)).getDate();
                    if(agendaDate != null  
                        && agendaDate.getYear() == inputDate.getYear() 
                        && agendaDate.getMonth() == inputDate.getMonth()) {
                        agendaList.add(new AgendaWrapper((Agenda)agendas.get(i)));
                    }
                }
            }
        }

        return new ModelAndView("showAgendas", Constants.AGENDA_LIST, agendaList);
    }
    
    
}
